import re
import time
import mss
import pyautogui
from API import YdmVerify
from PIL import Image
from PIL import ImageGrab
from paddleocr import PaddleOCR
pyautogui.FAILSAFE = False
ocr = PaddleOCR(det_model_dir='./inference/ch_PP-OCRv3_det_infer/',
                rec_model_dir='./inference/ch_PP-OCRv3_rec_infer/',
                cls_model_dir='./inference/ch_ppocr_mobile_v2.0_cls_infer/',
                use_angle_cls=True, lang="ch", use_gpu=False)

API = YdmVerify()


def get_ocr_result(img):
    # paddleocr 目前支持的多语言语种可以通过修改lang参数进行切换
    # 例如`ch`, `en`, `fr`, `german`, `korean`, `japan`
    # 使用CPU预加载，不用GPU
    # 识别图片文件
    result = ocr.ocr(img, cls=True)
    result = result[0]
    return result[0][1][0]


width, height = pyautogui.size()

img_path = 'element_screenshot.png'
while True:
    try:
        try:
            screenshot = ImageGrab.grab()
        except:
            sct = mss.mss()
            screenshot = sct.shot(output='element_screenshot.png')
        left = int(width * 0.38)
        top = int(height * 0.4)
        right = int(width * 0.60)
        bottom = int(height * 0.78)
        # 裁剪图片
        cropped_screenshot = screenshot.crop((left, top, right, bottom))
        cropped_width, cropped_height = cropped_screenshot.size
        # 显示裁剪后的图片
        # cropped_screenshot.show()
        cropped_screenshot.save(img_path)
        cont = get_ocr_result(img_path)

        if re.search('[a-zA-Z0-9]', cont):
            match = re.search('[a-zA-Z0-9]', cont)
            start_pos = match.start()
            end_pos = match.end()
            cont_ = list(cont)
            # print(start_pos)
            # print(cont_)
            cont_[start_pos - 1] = '"'
            try:
                cont_[start_pos + 1] = '"'
            except:
                cont_.append('"')
            print(cont_)
            cont = "".join(cont_)

        print("OCR识别结果：", cont)
        # cont='请点击侧对着你的字母"W"'

        if '找不到页面' not in cont and '点击' in cont:
            coord = YdmVerify().click_verify(image=img_path, extra=cont)
            x, y = coord.split(",")
            print("验证码解析位置：", x, y)
            pyautogui.click(left + int(x), top + int(y), duration=0.5)
        time.sleep(5)
        pyautogui.click(width*0.05, height*0.055, duration=0.5)
        time.sleep(5)
    except:
        pass
        continue